package com.lxd.api.filter.Impl;

import com.lxd.api.feign.cacheClient;
import com.lxd.api.filter.CheckFilter;
import com.lxd.common.constants.ApiConstant;
import com.lxd.common.constants.CacheConstant;
import com.lxd.common.enums.ExceptionEnums;
import com.lxd.common.exception.ApiException;
import com.lxd.common.model.StandardSubmit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service(value = "fee")
@Slf4j
public class FeeCheckFilter implements CheckFilter {

    @Autowired
    private cacheClient cacheClient;
    private final String BALANCE = "balance";

    @Override
    public void check(StandardSubmit submit) {


        // 根据clientId 从redis 查询客户 余额
        Long clientId = submit.getClientId();
        log.info("【接口模块-校验客户余额】当前客户clientid={}",clientId);
        Long balance =Long.valueOf(cacheClient.hgetString(CacheConstant.CLIENT_BALANCE + clientId, BALANCE));

        log.info("【接口模块-校验客户余额】当前余额还有balance={}", balance);
        // 计算短信的长度
        int length = submit.getText().length();
        // 短信的费用
        Long fee = 0L;
        //判断按70 还是 67 / 条计费
        if (length <= ApiConstant.MAX_LENGTH) {
            log.info("【接口模块-校验客户余额】短信内容长度<=70");
            fee = 1L;
        } else {
            log.info("【接口模块-校验客户余额】短信内容长度>70");
            int sum = length % ApiConstant.LOOP_LENGTH == 0 ? length % ApiConstant.LOOP_LENGTH : length % ApiConstant.LOOP_LENGTH;//计算有几条
            log.info("【接口模块-校验客户余额】短信有sum={}条", sum);
            fee = sum * 1L;
            log.info("【接口模块-校验客户余额】需要扣除fee={}", fee);
        }
        //设置当前短信费用
        submit.setFee(fee);

        if (fee <= balance) {
            log.info("【接口模块-校验客户余额】余额充足");

            return;

        }

        log.info("【接口模块-校验客户余额】余额不足！！");
        throw new ApiException(ExceptionEnums.BALANCE_NOT_ENOUGH);

    }
}
